package com.llc.spring.cloud.sdk.core.http;

import com.alibaba.fastjson.JSON;

import com.llc.spring.cloud.sdk.core.ex.RequestException;

import java.io.IOException;
import java.util.Map;

/**
 * time 2018/8/27 9:41
 *
 * @author xiaojie.zhu <br>
 */
public class DefaultHttpClient extends AbstractHttpClient {

    public DefaultHttpClient(String path, Map<String,Object> parameter, Object postBean , boolean get) {
        super(path, parameter, postBean, get);
    }


    @Override
    protected String request(){
        try {
            HttpRequest.Builder builder = HttpRequest.Builder.newBuilder();
            builder.url(this.toUrl());
            if(this.postBean != null){
                builder.json();
                String content = JSON.toJSONString(this.postBean);
                builder.stream(content.getBytes(utf8));
            }


            if(this.get){
                builder.get();
            }else{
                builder.post();
            }

            String response;
            HttpRequest.CloseableResponse closeableResponse = null;
            try {
                closeableResponse = builder.build().requestConnection();
                if(closeableResponse.responseCode() == 200){
                    response = closeableResponse.text();
                }else{
                    throw new RequestException("http请求失败" , closeableResponse.responseCode());
                }

            } finally {
                if(closeableResponse != null){
                    closeableResponse.close();
                }
            }
            return response;

        } catch (IOException e) {
            throw new RequestException(e.getClass().getName() + ":" + e.getMessage() , 505);
        }
    }
}
